<script setup lang="ts">
import { onMounted, onBeforeUnmount, ref, nextTick } from 'vue'
import * as echarts from 'echarts'
import { headersStore } from '@/stores/apiHeader'
import {
  DEFAULT_ECHARTS_FONTSIZE,
  DIALOG_ECHARTS_FONTSIZE,
} from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore

const fontSize = dialogInfo.visible
  ? DIALOG_ECHARTS_FONTSIZE
  : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

const language_id = headersStore().language_id
const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}

const normalArray = [...props.chartData?.data[0]?.line?.value]

let myChart: echarts.ECharts
const demo = () => {
  // 判断是否能获取到dom,如果不能直接结束
  const theDom = document.getElementById(props.chartData.name)
  if (!theDom) {
    return ''
  }
  myChart = echarts.init(document.getElementById(props.chartData.name))
  const option = {
    tooltip: {
      backgroundColor: 'rgba(0,0,0,0.7)',
      // trigger: 'axis',
      padding: [
        changePixelSize(10), // 上
        changePixelSize(20), // 右
        changePixelSize(10), // 下
        changePixelSize(20), // 左
      ],
      position:
        language_id == 'zh-cn'
          ? function (point, params, dom, rect, size) {
              const [pointX, pointY] = point
              const [boxWidth, boxHeight] = size.contentSize
              const x = boxWidth > pointX ? pointX + 10 : pointX - boxWidth - 10
              const y = boxHeight > pointY ? 5 : pointY - boxHeight
              return [x, y]
            }
          : function (pos, params, dom, rect, size) {
              // 鼠标在左侧时 tooltip 显示到右侧，鼠标在右侧时 tooltip 显示到左侧。
              var obj = { top: 30 }
              obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10
              return obj
            },
      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: function (params) {
          // 判断值是否包含负号
          return params.value.includes('-') ? 'red' : '#ffffff'
        },
      },
      formatter: function (params) {
        // 自定义悬浮框内容
        var color = params.value.includes('-') ? 'red' : '#ffffff'
        var value =
          params.componentSubType == 'bar'
            ? params.value
            : params.value + '%' || params.componentSubType == 'line'
            ? params.value + '%'
            : params.value
        return (
          '<span style="color:' +
          color +
          '">' +
          params.name +
          ': ' +
          value +
          '</span>'
        )
      },
    },
    color: ['#EB6456', '##EB6456', '#EE6666'], // 设置折线颜色
    legend: {
      data: [
        props.chartData?.data[0]?.bar?.name || '',
        props.chartData?.data[0]?.line?.name || '',
      ],
      itemWidth: changePixelSize(20),
      itemHeight: changePixelSize(10),
      textStyle: {
        fontSize: changePixelSize(fontSize),

        color: '#fff',
      },
    },
    grid: {
      left: '5%',
      right: '5%',
      bottom: '10%',
      top: '20%',
      containLabel: true,
    },
    yAxis: [
      {
        type: 'value',

        nameTextStyle: {
          color: '#fff',
          fontSize: changePixelSize(fontSize),
        },

        // min: min1,
        // max: max1,
        // interval: (max1 - min1) / 6,
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: function (value) {
            return value.includes('-') ? 'red' : '#ffffff'
          },
          margin: changePixelSize(5), // 调整标签与轴线的距离
          // formatter: function (params) {
          //   return params.toFixed(2)
          // },
        },
        axisTick: {
          show: false,
        },
        splitLine: {
          lineStyle: {
            color: '#123545', // 分割线颜色为灰色
          },
        },
      },
      {
        type: 'value',

        nameTextStyle: {
          color: '#fff',
          fontSize: changePixelSize(fontSize),
        },
        splitLine: {
          lineStyle: {
            color: '#123545', // 分割线颜色为灰色
            // z: 1, // 设置分割线的 z 轴值为 1
          },
        },
        // min: min2,
        // max: max2,
        // interval: (max2 - min2) / 6,
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: function (value) {
            return value.includes('-') ? 'red' : '#ffffff'
          },
          margin: changePixelSize(5), // 调整标签与轴线的距离
          formatter: function (params) {
            return params.toFixed(2) + '%'
          },
        },
        axisTick: {
          show: false,
        },
      },
    ],
    xAxis: {
      type: 'category',
      axisLine: { show: false },
      data: props.chartData?.xAxis.data,
      axisLabel: {
        show: true,
        color: '#fff',
        interval: 0,
        fontSize: changePixelSize(fontSize),
        margin: changePixelSize(fontSize), // 调整标签与轴线的距离
      },
      axisTick: { show: false },
      splitLine: { show: false },
    },
    series: [
      {
        name: props.chartData?.data[0]?.bar?.name,
        type: 'bar',
        barWidth: changePixelSize(36), // 设置柱状图的宽度
        data: props.chartData?.data[0]?.bar?.value,
        itemStyle: {
          color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
            { offset: 0, color: '#7C73F3' },
            { offset: 1, color: '#529BED' },
          ]),
        },
      },
      {
        name: props.chartData?.data[0]?.line?.name,
        type: 'line',
        yAxisIndex: 1,
        symbol: 'circle', //将小圆点改成实心 不写symbol默认空心
        symbolSize: changePixelSize(5), //小圆点的大小
        data: props.chartData?.data[0]?.line?.value,

        tooltip: {
          valueFormatter: function (value) {
            return !isNaN(Number(value)) ? value + ' %' : value
          },
        },
        label: {
          position: 'top',
          formatter: function (params) {
            return params.value + '%'
          },
        },
      },
    ],
  }
  myChart.setOption(option)
}
const destroyChart = () => {
  // 销毁图表实例
  if (myChart) {
    myChart.dispose()
    myChart = null
  }
}
onBeforeUnmount(() => {
  // 销毁图表实例
  destroyChart()
})
onMounted(() => {
  // 延迟渲染图表
  nextTick(() => {
    demo()
  })
})
</script>
<template>
  <div
    :class="{
      'echart-box': true,
      'dialog-box': dialogInfoVisible == true,
    }"
  >
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>

<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(260px); // 10px是指示器高度
  .chart {
    width: 100%;
    height: 100%;
  }
}

.dialog-box {
  height: calc(500px - 45px);
}
</style>
